package com.flyduck.system.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyduck.common.util.CollectionUtil;
import com.flyduck.system.entity.SysRoleMenuEntity;
import com.flyduck.system.mapper.SysRoleMenuMapper;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: flyduck-platform2
 * @description:
 * @author: flyduck
 * @create: 2021-04-23 14:53
 **/
@Repository
public class SysRoleMenuDao extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuEntity> {

    /**
     * 根据角色id集合获取菜单id集合
     * @param roleIds
     * @return
     */
    public List<Long> getMenuIdsByRoleIds(List<Long> roleIds) {
        List<SysRoleMenuEntity> sysRoleMenuEntityList = this.baseMapper.selectList(
                new QueryWrapper<SysRoleMenuEntity>().in("role_id", roleIds)
        );
        if(CollectionUtil.isEmpty(sysRoleMenuEntityList)){
            return Lists.newArrayList();
        }
        return sysRoleMenuEntityList.stream().map(SysRoleMenuEntity::getMenuId).distinct().collect(Collectors.toList());
    }

    /**
     * 新增角色菜单关系集合
     * @param roleId
     * @param menuIds
     * @return
     */
    public int insertRoleMenuList(Long roleId, List<Long> menuIds) {
        int rows = 0;
        for (Long menuId : menuIds) {
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setRoleId(roleId);
            sysRoleMenuEntity.setMenuId(menuId);
            int row = this.baseMapper.insert(sysRoleMenuEntity);
            rows += row;
        }
        return rows;
    }

    /**
     * 根据角色id删除角色菜单关系
     * @param roleId
     * @return
     */
    public int deleteByRoleId(Long roleId) {
        return this.baseMapper.delete(new QueryWrapper<SysRoleMenuEntity>().eq("role_id", roleId));
    }

}
